package com.youlu.campus.starter.sms.sender;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.github.qcloudsms.httpclient.HTTPException;
import com.youlu.campus.starter.sms.properties.SmsTencentProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Objects;

/**
 * 短信工具类
 *
 * @author: zhuhuaiqi
 * @date: 2018/9/11 14:21
 */
@Slf4j
@Component
public class SmsTencentSender {

    @Autowired
    private SmsTencentProperties smsTencentProperties;


    /**
     * 发送短信信息
     *
     * @param phone
     * @param templateId
     * @param params
     * @return
     */
    public boolean sendWithParam(String smsSign, String phone, int templateId, String... params) {
        try {
            SmsSingleSender ssender = new SmsSingleSender(smsTencentProperties.getAppid(), smsTencentProperties.getAppkey());
            SmsSingleSenderResult result = ssender.sendWithParam("86", phone, templateId, params, smsSign, "", "");
            log.info("发送短信返回结果：{}", JSON.toJSONString(result));
            if (Objects.nonNull(result) && result.result != 0) {
                log.error(":>>> 短信发送结果为空,或是返回码不是成功");
                return false;
            }

        } catch (HTTPException e) {
            // HTTP 响应码错误
            e.printStackTrace();
        } catch (JSONException e) {
            // JSON 解析错误
            e.printStackTrace();
        } catch (IOException e) {
            // 网络 IO 错误
            e.printStackTrace();
        }
        return true;
    }
}
